package com.yuexun.dhdoctor.module.healthRecord.ui;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;


import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.BaseEntity;
import com.yuexun.dhdoctor.base.BaseKJActivity;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.healthRecord.adapter.HealthRecordAdapter;
import com.yuexun.dhdoctor.module.healthRecord.bean.HealthRcordBean;
import com.yuexun.dhdoctor.module.healthRecord.model.impl.HealthRecordModel;
import com.yuexun.dhdoctor.module.healthRecord.presenter.IHealthRecordPresenter;
import com.yuexun.dhdoctor.module.healthRecord.presenter.impl.HealthRecordPresenter;
import com.yuexun.dhdoctor.module.healthRecord.ui.impl.IHealthRecordView;
import com.yuexun.dhdoctor.widget.EmptyLayout;
import com.yuexun.dhdoctor.widget.PullToRefresh.FooterLoadingLayout;
import com.yuexun.dhdoctor.widget.PullToRefresh.PullToRefreshBase;
import com.yuexun.dhdoctor.widget.PullToRefresh.PullToRefreshList;

import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by work-jx on 2016/4/14.
 */
public class Act_HealthRecord extends BaseKJActivity implements IHealthRecordView {
    @Bind(R.id.title_tv)
    TextView titleTv;
    @Bind(R.id.filter_edittext)
    EditText filterEdittext;
    @Bind(R.id.healthrecord_list)
    PullToRefreshList healthrecordList;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;

    private ListView mList;
    private HealthRecordAdapter adapter;

    private int nowpage = 1;
    private int pagesize = 20;

    IHealthRecordPresenter presenter;

    List<HealthRcordBean.RowsBean> rowsBeans = new ArrayList<>();

    @Override
    public void setRootView() {
        setContentView(R.layout.act_healthrecord);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        presenter = new HealthRecordPresenter(this, new HealthRecordModel());
        listViewPreference();
        setTitle();
        filterEdittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (adapter != null) {
                    adapter.getFilter().filter(s.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        ApiForGetList();
    }

    //请求详情
    private void ApiForGetList() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("pageIndex", nowpage+"");
        params.put("pageSize", pagesize+"");
        params.put("hospId", "41955956");
        params.put("empId", "666");
        presenter.showHealthRecordData(params);
    }

    /**
     * 初始化ListView样式
     */
    private void listViewPreference() {
        mList = healthrecordList.getRefreshView();
        mList.setDivider(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
        mList.setOverscrollFooter(null);
        mList.setOverscrollHeader(null);
        mList.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
        healthrecordList.setPullLoadEnabled(true);//设置上拉刷新功能关闭
        ((FooterLoadingLayout) healthrecordList.getFooterLoadingLayout())
                .setNoMoreDataText("已经是最新状态");

        adapter = new HealthRecordAdapter(mList, rowsBeans, R.layout.importmentpatient_item);
        mList.setAdapter(adapter);

        healthrecordList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                nowpage = 1;
                ApiForGetList();
            }

            @Override
            public void onPullUpToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                nowpage = nowpage + 1;
                ApiForGetList();
            }
        });

        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                nowpage = 1;
                ApiForGetList();
            }
        });
    }

    @OnClick(R.id.back)
    public void onClick() {
        finish();
    }

    protected void setTitle() {
        titleTv.setText("健康档案");
    }

    /**
     * 通过dispatchTouchEvent每次ACTION_DOWN事件中动态判断非EditText本身区域的点击事件，然后在事件中进行屏蔽。然后当点击不是EditText时候，进行隐藏键盘操作
     *
     * @param ev
     * @return
     */

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {

        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件\
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    @Override
    public void showHealthRecordDate(BaseEntity<HealthRcordBean> list) {
        if (healthrecordList.isPullRefreshEnabled()) {
            healthrecordList.onPullDownRefreshComplete();
        }

        if (list.getStatus().equals("200")) {
            if (list.getDatas().size() == 0) {
                healthrecordList.setHasMoreData(false);
            } else {
                if (healthrecordList.isPullLoadEnabled()) {
                    healthrecordList.onPullUpRefreshComplete();
                }
            }

            if (nowpage == 1) {
                rowsBeans.clear();
                rowsBeans = list.getDatas().get(0).getRows();
            } else {
                rowsBeans.addAll(list.getDatas().get(0).getRows());
            }
            adapter.refresh(rowsBeans);
        } else {
            ViewInject.toast(list.getMessage());
        }

        if (list.getDatas().size() == 0) {
            emptyLayout.setErrorType(EmptyLayout.NODATA);
        } else {
            emptyLayout.dismiss();
        }
    }
}
